package com.yuerlive.rainbow.widget;

import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.RelativeLayout;


public class ResizeLayout extends RelativeLayout {
	 
	 private static final String TAG="ResizeLayout";
    private OnkeyboardShowListener mChangedListener;
    private boolean misKeyboardshow = false;
    private  int heightDiff=0;
    /**
     * @param context
     * @param attrs
     */
    public ResizeLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
     
    public static interface OnkeyboardShowListener {
        public void onKeyboardShow(int height);
        public void onKeyboardHide();
    }
 
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
            int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }
     
    public boolean isKeyboardShowing() {
        return misKeyboardshow;
    }
 
    public void setOnKeyboardShowListener(OnkeyboardShowListener listener) {
        mChangedListener = listener;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //TODO 不知道为什么软键盘弹出时候获取的proposedHeight高度没有变化
//        final int proposedHeight = MeasureSpec.getSize(heightMeasureSpec);
//        final int actualHeight = getHeight();
//
//        if (actualHeight > proposedHeight) {
//            L.e("keyboard", "guess keyboard is shown"+actualHeight+":::"+proposedHeight);
//        } else {
//            L.e("keyboard", "guess keyboard has been hidden"+actualHeight+":::"+proposedHeight);
//        }
        if(mChangedListener!=null) {
            if (isKeyboardShown(this.getRootView())) {
                mChangedListener.onKeyboardShow(heightDiff);
            } else {
                mChangedListener.onKeyboardHide();
            }
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    /**
     *  根据rootView可见高度和rootView高度之差去判断软键盘是否弹起
     * @param rootView
     * @return
     */
    private boolean isKeyboardShown(View rootView) {
        final int softKeyboardHeight = 100;
        Rect r = new Rect();
        rootView.getWindowVisibleDisplayFrame(r);
        DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
        heightDiff = rootView.getBottom() - r.bottom;
        return heightDiff > softKeyboardHeight * dm.density;
    }
}